package com.wqd.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wqd.apis.article.IArticleClient;
import com.wqd.common.aliyun.GreenImageScan;
import com.wqd.common.aliyun.GreenTextScan;
import com.wqd.common.tess4j.Tess4jClient;
import com.wqd.file.service.FileStorageService;
import com.wqd.model.article.dtos.ArticleDto;
import com.wqd.model.common.dtos.ResponseResult;
import com.wqd.model.wemedia.pojos.WmChannel;
import com.wqd.model.wemedia.pojos.WmNews;
import com.wqd.model.wemedia.pojos.WmSensitive;
import com.wqd.model.wemedia.pojos.WmUser;
import com.wqd.utils.common.SensitiveWordUtil;
import com.wqd.wemedia.mapper.WmChannelMapper;
import com.wqd.wemedia.mapper.WmNewsMapper;
import com.wqd.wemedia.mapper.WmSensitiveMapper;
import com.wqd.wemedia.mapper.WmUserMapper;
import com.wqd.wemedia.service.WmNewsAutoScanService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RestController
@Transactional
public class WmNewsAutoScanServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 自媒体文章审核
     * @param id
     */
    @Override
    @Async  //异步调用方法
    public void autoScanWmNews(Integer id) {
        //查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if(wmNews == null){
            throw new RuntimeException("WmNewsAutoScanServiceImpl----文章不存在");
        }
        //判断是不是提交状态的
        if(wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            //从内容中获取图片和文本封装到Map中
            Map<String,Object> textAndImages = handleTextAndImages(wmNews);

            //自定义敏感词过滤
            boolean isSensitive = handleSensitiveScan((String)textAndImages.get("content"),wmNews);
            if(!isSensitive){
                return;
            }

            //阿里云文本审核
            /*if(!handleTextScan((String) textAndImages.get("content"),wmNews)){
                return;
            }*/

            //阿里云图片审核
            /*if(!handleImageScan((List<String>) textAndImages.get("images"),wmNews)){
                return;
            }*/

            //审核成功,保存文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);
            if(!responseResult.getCode().equals(200)){
                throw new RuntimeException("WmNewsAutoScanServiceImpl----保存文章失败");
            }

            wmNews.setArticleId((Long)responseResult.getData());
            updateWmNews(wmNews,(short)9,"审核成功");
        }
    }


    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    /**
     * 自定义敏感词过滤
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        boolean flag = true;
        //获取自定义的敏感词列表
        List<WmSensitive> wmSensitiveList = wmSensitiveMapper.selectList(null);
        List<String> sensitives = wmSensitiveList.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词列表
        SensitiveWordUtil.initMap(sensitives);
        //判断是否存在敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if(map.size() > 0){
            updateWmNews(wmNews, (short) 2,"文章存在违规内容" + map);
            flag = false;
        }
        return flag;
    }


    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private IArticleClient articleClient;


    /**
     * 保存数据,封装结果
     * @param wmNews
     * @return
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,dto);
        //补充文章布局
        dto.setLayout(wmNews.getType());
        //频道设置
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        //判断是否存在这个频道
        if(wmChannel != null){
            dto.setChannelName(wmChannel.getName());
        }

        //作者设置
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser != null){
            dto.setAuthorName(wmUser.getName());
        }

        //文章id设置
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }
        //时间
        dto.setCreatedTime(new Date());

        //远程调用保存文章信息
        ResponseResult responseResult = articleClient.saveArticle(dto);

        return responseResult;

    }


    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 图片审核实现
     * @param images
     * @param wmNews
     * @return  返回是否违规
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag = true;
        if(images == null || images.size() == 0){
            return flag;
        }
        //下载图片
        //图片去重
        images = images.stream().distinct().collect(Collectors.toList());

        List<byte[]> imageList = new ArrayList<>();
        for (String image : images) {
            imageList.add(fileStorageService.downLoadFile(image));
        }

        //图片OCR审核
        try {
            for (byte[] bytes : imageList) {
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                BufferedImage imageFile = ImageIO.read(in);
                //图片识别文字
                String result = tess4jClient.doOCR(imageFile);
                //自定义敏感词审核
                if(!handleSensitiveScan(result,wmNews)){
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        try {
            //批量审核图片
            Map map = greenImageScan.imageScan(imageList);
            if(map != null){
                //审核不通过
                if(map.get("suggestion").equals("block")){
                    flag = false;
                    updateWmNews(wmNews,(short)2,"当前文章存在违规内容");
                }
                if(map.get("suggestion").equals("review")){
                    flag = false;
                    updateWmNews(wmNews,(short)3,"当前文章存在疑似违规内容,需要人工介入");
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }

        return flag;
    }


    @Autowired
    private GreenTextScan greenTextScan;

    /**
     * 阿里云文本审核方法
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        if((wmNews.getTitle() + content).length() == 0){
            return flag;
        }
        try {
            //调用接口
            Map map = greenTextScan.greeTextScan(wmNews.getTitle() + "----" + content);
            if(map != null){
                //审核不通过
                if(map.get("suggestion").equals("block")){
                    flag = false;
                    updateWmNews(wmNews,(short)2,"当前文章存在违规内容");
                }
                if(map.get("suggestion").equals("review")){
                    flag = false;
                    updateWmNews(wmNews,(short)3,"当前文章存在疑似违规内容,需要人工介入");
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 修改文章内容
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        updateById(wmNews);
    }

    /**
     * 封装方法: 用于获取内容中的图片和文本
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        String content = wmNews.getContent();
        //创建一个集合存放图片
        List<String> images = new ArrayList<>();
        //创建一个StringBuilder存放文本内容
        StringBuilder allContent = new StringBuilder();
        allContent.append(wmNews.getTitle());
        allContent.append(wmNews.getLabels());

        if(StringUtils.isNotBlank(content)){
            List<Map> maps = JSONArray.parseArray(content,Map.class);
            for (Map map : maps) {
                if(map.get("type").equals("text")){
                    allContent.append(map.get("value"));
                }
                if(map.get("type").equals("image")){
                    images.add((String) map.get("value"));
                }
            }
        }
        //提取封面图片
        if(StringUtils.isNotBlank(wmNews.getImages())){
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        Map<String, Object> rsMap = new HashMap<>();
        rsMap.put("content",allContent.toString());
        rsMap.put("images",images);
        return rsMap;
    }

}
